package com.hpin.mlxteacher.message;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.hpin.mlxteacher.R;
import com.hpin.mlxteacher.adapter.ImageAdapter;
import com.hpin.mlxteacher.adapter.MyAdapter;
import com.hpin.mlxteacher.base.BaseActivity;
import com.hpin.mlxteacher.bean.BitmapDetail;
import com.hpin.mlxteacher.bean.MessageSend;
import com.hpin.mlxteacher.bean.SchoolResultBean;
import com.hpin.mlxteacher.bean.UploadBean;
import com.hpin.mlxteacher.utils.CommonUtils;
import com.hpin.mlxteacher.utils.Constant;
import com.hpin.mlxteacher.utils.HttpUtil;
import com.hpin.mlxteacher.utils.LogUtil;
import com.hpin.mlxteacher.widget.ActionSheetDialog;
import com.hpin.mlxteacher.widget.GridViewForScrollView;
import com.hpin.mlxteacher.widget.PreviewPhotoActivity;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

//import com.umeng.analytics.MobclickAgent;

/**
 * 编辑信息页面
 * Created by Aaron on 2015/7/20.
 */
public class EditMessageActivity extends BaseActivity {

    /**
     * 分类code
     */
    private static final int CLASSIFY_CODE = 1007;
    /* 收件人code*/
    private static final int RECEIVER_CODE = 1008;
    /*相册选择的code*/
    private static final int PHOTO_ALBUM_CODE = 101;
    /*拍照的code*/
    private static final int TAKE_PHOTO_CODE = 102;
    /* 分类*/
    private TextView tv_classify;
    private ImageView iv_delete_title;
    private EditText et_title;
    private EditText et_content;
    private GridViewForScrollView gv_photos;
//    private ExecutorService executor;
    //需要上传的图片的数量
    private int uploadCount;
    //存放上传的图片的集合
    public List<BitmapDetail> loadedPics = new ArrayList<BitmapDetail>();
    public List<String> url = new ArrayList<String>();
    //    public List<String> childIds = new ArrayList<String>();
    public List<String> schoolIds = new ArrayList<String>();
    /**
     * 当前上传的图片的个数
     */
    int currentUpPic = 0;
    /*拍照的文件保存的位置*/
    private File currentFile;
//    //当前GridView展示的图片的集合
//    private ArrayList<String> currentShowPhotos = new ArrayList<String>();
    /**
     * Gridview 存放的图片的集合
     */
    private ArrayList<BitmapDetail> bitmapList;
    //用于添加有效图片的 + 号 图片 本地地址和url地址都为 虚构
    private BitmapDetail addBitmapDeail;

    private ImageAdapter imageAdapter;
    //当前要发送的消息的类型code
    private String currentClassifyCode;
    private TextView tv_receivers;
    //    private StringBuilder sbId = new StringBuilder();
    private ProgressDialog pdialog;
    private String sendId;
    private int style = 0;//0是学校 1是孩子
    //是否是通讯录跳转到编辑信息页面的 是的话不可再次选择联系人
    private boolean isAdress = false;

//    public final String IMAGE_UNSPECIFIED = "image/*";
//    public static final int PHOTO_RESOULT = 1043;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_edit);

        //通讯录过来的 发送人 和 发送人的ID
        String sendName = getIntent().getStringExtra("sendName");
        sendId = getIntent().getStringExtra("sendId");
        //是否是通讯录跳转到编辑信息页面的
        isAdress = getIntent().getBooleanExtra("isAdress", false);

        initWidget();

        if (!CommonUtils.isNull(sendName) && !CommonUtils.isNull(sendId)) {
            tv_receivers.setText(sendName);
            schoolIds.add(sendId);
        }
    }

    private void initWidget() {

//        currentShowPhotos.add(Constant.ADDBITMAPPATH);

        ImageView tv_left = (ImageView) findViewById(R.id.iv_left);
        TextView tv_title = (TextView) findViewById(R.id.tv_title);
        TextView tv_right = (TextView) findViewById(R.id.tv_right);

        tv_title.setText(getResources().getString(R.string.new_message));
        tv_right.setText(getResources().getString(R.string.send_message));

        tv_left.setOnClickListener(this);
        tv_right.setOnClickListener(this);

        tv_classify = (TextView) findViewById(R.id.tv_classify);
        iv_delete_title = (ImageView) findViewById(R.id.iv_delete_title);
        ImageView iv = (ImageView) findViewById(R.id.iv);
        RelativeLayout rl_classify = (RelativeLayout) findViewById(R.id.rl_classify);
        RelativeLayout rl_receiver_people = (RelativeLayout) findViewById(R.id.rl_receiver_people);

        tv_receivers = (TextView) findViewById(R.id.tv_receivers);

        et_title = (EditText) findViewById(R.id.et_title);
        et_content = (EditText) findViewById(R.id.et_content);

        gv_photos = (GridViewForScrollView) findViewById(R.id.gv_photos);

        rl_classify.setOnClickListener(this);
        //
        if (!isAdress) {
            rl_receiver_people.setOnClickListener(this);
        }else{
            iv.setVisibility(View.INVISIBLE);
        }
        iv_delete_title.setOnClickListener(this);

        et_title.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (b) {//获得焦点
                    iv_delete_title.setVisibility(et_title.getText().toString().length() > 0 ? View.VISIBLE : View.INVISIBLE);
                    et_title.addTextChangedListener(new TextWatcher() {
                        @Override
                        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                        }

                        @Override
                        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                        }

                        @Override
                        public void afterTextChanged(Editable editable) {
                            iv_delete_title.setVisibility(et_title.getText().toString().length() > 0 ? View.VISIBLE : View.INVISIBLE);
                        }
                    });

                } else {//未获得焦点
                    iv_delete_title.setVisibility(View.INVISIBLE);
                }
            }
        });

        initGrideView();

    }

    /**
     * 初始化GrideView
     */
    private void initGrideView() {

        bitmapList = new ArrayList<BitmapDetail>();

        //先添加 + 号图片
        Bitmap addBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.icon_add);
        addBitmapDeail = new BitmapDetail(Constant.ADDBITMAPPATH, Constant.ADDBITMAPPATH);

        bitmapList.add(addBitmapDeail);
        imageAdapter = new ImageAdapter(this, bitmapList, pics);
        gv_photos.setAdapter(imageAdapter);

        gv_photos.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                //点击的是图片的最后一个
                if (loadedPics.size() == 0 || loadedPics.size() == position) {

                    if (loadedPics.size() == 9) {
                        Intent mIntent = new Intent(EditMessageActivity.this, PreviewPhotoActivity.class);
                        mIntent.putExtra("position", position);
                        mIntent.putExtra("lists", (Serializable) loadedPics);
                        startActivity(mIntent);
                        return;
                    }

                    //添加照片 弹出选择对话框
                    showChoose();

                } else {

                    //查看照片
                    Intent mIntent = new Intent(EditMessageActivity.this, PreviewPhotoActivity.class);
                    mIntent.putExtra("position", position);
                    mIntent.putExtra("lists", (Serializable) loadedPics);
                    startActivity(mIntent);

                }
            }
        });

    }


    @Override
    public void widgetClick(View v) {

        switch (v.getId()) {

            case R.id.iv_left:
                //返回
                abandonEdit();

                break;
            case R.id.iv_delete_title:
                //删除录入的标题
                et_title.setText("");

                break;
            case R.id.tv_right:
                //发送
                sendMessage();
                break;

            case R.id.rl_classify:
                //分类
                Intent classifyIntent = new Intent(this, ClassifyActivity.class);
                startActivityForResult(classifyIntent, CLASSIFY_CODE);

                break;
            case R.id.rl_receiver_people:
                //收件人
                Intent intent = new Intent(this, ReceiverActivity.class);
                startActivityForResult(intent, RECEIVER_CODE);

                break;

        }
    }

    /**
     * 发送消息
     */
    private void sendMessage() {

        if (CommonUtils.isNull(tv_classify.getText().toString().trim())) {
            showToast("请选择分类");
            return;
        }

        if (CommonUtils.isNull(tv_receivers.getText().toString().trim())) {
            showToast("请选择收件人");
            return;
        }

        if (CommonUtils.isNull(et_title.getText().toString().trim())) {
            showToast("请输入标题");
            return;
        }

        if (CommonUtils.isNull(et_content.getText().toString().trim())) {
            showToast("请输入内容");
            return;
        }

        MessageSend messageSend = new MessageSend();
        messageSend.token = sp.getString(Constant.token, "");
        messageSend.type = currentClassifyCode;
//        messageSend.type = sendId;
//        messageSend.receiveList = sbId.toString().substring(0, sbId.length() - 1);
//        messageSend.receiveList.childList = schoolIds;

        //messageSend外部类.new一个内部类,否则会报空指针

        messageSend.receiveList = messageSend.new ReceiveList();

        if (style == 0) {//0是学校
            messageSend.receiveList.teacherList = schoolIds;
            messageSend.receiveList.childList = null;
        } else if (style == 1) {//1是孩子
            messageSend.receiveList.childList = schoolIds;
            messageSend.receiveList.teacherList = null;
        } else {
            showToast("请选择收件人");
            return;
        }
//        messageSend.receiveList.teacherList = schoolIds;

        messageSend.title = et_title.getText().toString().trim();
        messageSend.content = et_content.getText().toString().trim();

        //图片
//        StringBuilder urls = new StringBuilder();
        for (BitmapDetail b : loadedPics) {
            url.add(b.urlPath + "");
//            urls.append(b.urlPath + ",");

        }

        messageSend.imgList = url;
//        messageSend.imgList = loadedPics.size() == 0 ? "" : urls.toString().substring(0, urls.length() - 1);

        String jsonString = JSONObject.toJSONString(messageSend);

        HttpUtil.setPostRequest("发送中...", this, Constant.WEB_ROOT + Constant.SENDMSG, jsonString
                , getClass().getName(), new HttpUtil.SuccessListener() {
            @Override
            public void setOnSuccessListener(String str) {

                try {

                    org.json.JSONObject result = new org.json.JSONObject(str);

                    if (result.getInt("code") == Constant.SUCCESS) {

                        showToast("发送成功");
                        finish();

                    } else {
                        showToast(Constant.showErrorMsg(result.getInt("code"), EditMessageActivity.this));
                    }

                } catch (Exception e) {

                    e.printStackTrace();
                    showToast(Constant.NODATA);

                }

            }
        }, null);

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {

            case RECEIVER_CODE:     //收件人

                if (data == null)
                    return;

                //获得到选中的接受人
                List<SchoolResultBean.Data> chooseedPeoples = (List<SchoolResultBean.Data>) data.getSerializableExtra("chooseedPeoples");
                //获得选中的类型
                style = data.getIntExtra("style", -1);

                if (chooseedPeoples == null || chooseedPeoples.size() < 1)
                    return;

                StringBuilder sb = new StringBuilder();

                for (SchoolResultBean.Data p : chooseedPeoples) {

                    sb.append(p.nickName + ",");

//                    sbId.append(p.id + ",") ;
                    schoolIds.add(p.id);
//                    childIds.add( p.id );
                }

                tv_receivers.setText(sb.toString().substring(0, sb.length() - 1));

                break;


            case CLASSIFY_CODE:    //分类

                if (data == null)
                    return;

                currentClassifyCode = data.getStringExtra("classifyCode");

                if (Constant.MSG_MESSAGE.equals(currentClassifyCode)) {

                    tv_classify.setText(getResources().getString(R.string.rl_news));

                } else if (Constant.MSG_UNFINISHED_WORK.equals(currentClassifyCode)) {
                    tv_classify.setText(getResources().getString(R.string.message_todo));
                } else if (Constant.MSG_NOTIFICATION.equals(currentClassifyCode)) {
                    tv_classify.setText(getResources().getString(R.string.message_notice));
                }

                break;

            case TAKE_PHOTO_CODE:       //拍照
                //上传图片
                if (currentFile != null && currentFile.exists()) {
                    pdialog = ProgressDialog.show(this, "", "图片上传中...");
                    loadPicToNet(currentFile.getPath());

//                LogUtil.e("TAG", "拍照的图片的地址====>>>" + currentFile.getPath());
                }


                break;

            case PHOTO_ALBUM_CODE:       //选择照片
                if (data == null){
                    clearCachePhoto();
                    return;
                }

                //获取到传过来的图片的集合
                ArrayList<String> tempPhotos = data.getStringArrayListExtra("selectedPhotos");
                handleChoosedPhoto(tempPhotos);
                break;
        }

    }

    public void clearCachePhoto() {
        //循环myadapter里面的所选择图片的路径
//        for (String paths : MyAdapter.mSelectedImage) {

        //如果pics里面存在myadapter里面的所选择图片的路径,则不清除所选图片

        Iterator<String> it = MyAdapter.mSelectedImage.iterator();
//
        while (it.hasNext()) {
            //it是迭代器你把集合中的所有元素都装入迭代器中
            //it.next()是迭代器提供给你的去他里面元素的方法
            String next = it.next();
            if (pics.contains(next)) {

                continue;
            }else
                it.remove();
//            MyAdapter.mSelectedImage.remove(next);
        }
    }
    /**
     * 处理相册选择的图片
     *
     * @param tempPhotos
     */
    ArrayList<String> pics = new ArrayList<String>();
    private void handleChoosedPhoto(ArrayList<String> tempPhotos) {

        if (tempPhotos != null && tempPhotos.size() > 0) {

            for (String path : tempPhotos) {

                if (pics.contains(path)){
                    continue;
                }else{
                    pics.add(path);
                    if (++uploadCount == 1) {//上传个数+1, 如果是第一张图片就显示转圈
                        pdialog = ProgressDialog.show(this, "", "图片上传中...");
                    }

                    loadPicToNet(path);
                }


//                LogUtil.e("TAG", "选择的照片的路径==>" + path);
//                //是否存在
//                boolean exist = false;
//
//                //判断图片是否已经上传过,如果已经上传过就不需要再上传了
//                for (BitmapDetail bd : loadedPics) {
//
//                    if (path.equals(bd.mPath)) {
//                        //已经存在了该图片,无需再次上传
//                        exist = true;
//                        break;
//                    }
//
//                }
//
//                if (!exist) { //没有上传过,需要上传
//
//                    if (++uploadCount == 1) {//上传个数+1, 如果是第一张图片就显示转圈
//                        pdialog = ProgressDialog.show(this, "", "图片上传中...");
//                    }
//
//                    loadPicToNet(path);
//                }

            }

        }

    }

    /**
     * 上传图片
     *
     * @param picturePath 该图片在手机上的地址
     */
    private void loadPicToNet(String picturePath) {

//        if (executor == null)
//            executor = Executors.newSingleThreadExecutor();
//
//        executor.execute(loadToNet(CommonUtils.compressByte(CommonUtils.getBitmapFromPath(picturePath)), picturePath));
        loadToNet(CommonUtils.compressByte(CommonUtils.getBitmapFromPath(picturePath)), picturePath);
    }

    /**
     * 获取上传的token 并上传图片
     *
     * @param bytes       上传图片的 字节码
     * @param picturePath 上传图片的本地地址
     */
    private void loadToNet(final byte[] bytes, final String picturePath) {

        JSONObject j = new JSONObject();
        j.put("token", sp.getString(Constant.token, ""));

        HttpUtil.setPostRequest("加载中...", this, Constant.WEB_ROOT + "uploadToken", j.toJSONString(),
                null, new HttpUtil.SuccessListener() {

            @Override
            public void setOnSuccessListener(String str) {

                LogUtil.e("tag", "返回的token==" + str);

                final UploadBean uploadBean = JSONObject.parseObject(str, UploadBean.class);

                if (uploadBean.code == Constant.SUCCESS) {

                    UploadManager uploadManager = new UploadManager();

                    uploadManager.put(bytes, uploadBean.path, uploadBean.token,
                            new UpCompletionHandler() {
                                @Override
                                public void complete(String s, ResponseInfo responseInfo, org.json.JSONObject jsonObject) {

                                    //  res 包含hash、key等信息，具体字段取决于上传策略的设置。
                                    Log.e("qiniu", s + ",\r\n " + responseInfo + ",\r\n " + jsonObject);

                                    if (responseInfo.isOK()) {


                                        //最后一张图片才会销毁 dialog
                                        if (++currentUpPic >= uploadCount) {

                                            if (pdialog != null && pdialog.isShowing()) {

                                                pdialog.dismiss();
//                                                LogUtil.e("TAG", "消失了???==>" + currentUpPic + ",,=>" + uploadCount);

                                                currentUpPic = 0;
                                                uploadCount = 0;
                                            }
                                        }

//                                        imageUrl = uploadBean.domain + uploadBean.path + uploadBean.thumb;
                                        addPicToPage(new BitmapDetail(picturePath, uploadBean.domain + uploadBean.path));

                                    } else {
                                        showToast("图片上传失败");
                                    }

//                                    LogUtil.e("tag", "是否上传成功=====" + ok);

                                }

                            }, null);

                } else {
                    showToast(Constant.showErrorMsg(uploadBean.code, EditMessageActivity.this));
                }

            }
        }, null);

    }
//    /**
//     * 上传图片的runnable
//     *
//     * @param bytes       图片的字节数组
//     * @param picturePath 图片的本地路径
//     * @return
//     */
//    private Runnable loadToNet(final byte[] bytes, final String picturePath) {
//
//        return new Thread() {
//            @Override
//            public void run() {
//
//                String upResult = HttpUtil.getInstance().load(Constant.WEB_ROOT + Constant.uploadPic + "/" + sp.getString(Constant.token, ""), bytes);
//
////				LogUtil.e("TAG", "上传图片返回的upResult==" + upResult);
//
//                Message loadMsg = Message.obtain();
//
//                try {
//
//                    LoadPicResult loadPicResult = JSONObject.parseObject(upResult, LoadPicResult.class);
//
//                    if (loadPicResult.code == Constant.SUCCESS) {
//
//                        //上传成功
//
//                        loadMsg.what = LOADSUCCESS;
//
//                        loadMsg.obj = new BitmapDetail(picturePath, loadPicResult.url);
//
//                    } else {
//                        loadMsg.what = LOADERR;
//                    }
//
//                } catch (Exception e) {
//                    loadMsg.what = LOADERR;
//                    e.printStackTrace();
//                } finally {
//
//                    handler.sendMessage(loadMsg);
//                }
//
//            }
//        };
//    }
//
//    /**
//     * 当前上传的图片的个数
//     */
//    int currentUpPic = 0;
//
//    private Handler handler = new Handler() {
//
//        @Override
//        public void handleMessage(Message msg) {
//
//            //最后一张图片才会销毁 dialog
//            if (++currentUpPic >= uploadCount) {
//
//                if (pdialog != null && pdialog.isShowing()) {
//
//                    pdialog.dismiss();
//                    LogUtil.e("TAG", "消失了???==>" + currentUpPic + ",,=>" + uploadCount);
//
//                    currentUpPic = 0;
//                    uploadCount = 0;
//                }
//            }
//
//            switch (msg.what) {
//                case LOADSUCCESS:// 图片上传 成功
//
//                    addPicToPage((BitmapDetail) msg.obj);
//
//                    break;
//
//                case LOADERR:// 图片上传 失败
//
//                    showToast("图片上传失败");
//
//                    break;
//
//                default:
//                    break;
//            }
//
//        }
//
//    };

//    /**
//     * 页面上添加图片
//     *
//     * @param mBitmapDetail BitmapDetail对象,包含了图片的本地路径和url路径
//     */
//    private void addPicToPage(BitmapDetail mBitmapDetail) {
//
//        // 先移除用来添加的图标，再添加以保证添加的图片始终在最后
//        bitmapList.remove(addBitmapDeail);
//        //上传成功后再添加图片
//        bitmapList.add(mBitmapDetail);
//        loadedPics.add(mBitmapDetail);
////        LogUtil.e("TAG", "添加的图片的路径的====>" + mBitmapDetail.mPath);
//
//        //如果有效图片小于9张 就添加 + 号图片
//        if (bitmapList.size() < 9) {
//            bitmapList.add(addBitmapDeail);
//        }
//        //
//        imageAdapter.setBitmapsDetail(bitmapList, pics);
//        imageAdapter.notifyDataSetChanged();
//
//    }

    /**
     * 页面上添加图片
     *
     *
     * @param mBitmapDetail BitmapDetail对象,包含了图片的本地路径和url路径
     */
    private void addPicToPage(BitmapDetail mBitmapDetail) {
//
//        // 先移除用来添加的图标，再添加以保证添加的图片始终在最后
//        bitmapList.remove(addBitmapDeail);
        // 先移除用来添加的图标，再添加以保证添加的图片始终在最后
        if (bitmapList.size() > 0)//??
            bitmapList.remove(bitmapList.size() - 1);
        //上传成功后再添加图片
        bitmapList.add(mBitmapDetail);
        loadedPics.add(mBitmapDetail);
//        LogUtil.e("TAG", "添加的图片的路径的====>" + mBitmapDetail.mPath);

        //如果有效图片小于9张 就添加 + 号图片
        if (bitmapList.size() < 9) {
            bitmapList.add(addBitmapDeail);
        }
        //
        imageAdapter.setBitmapsDetail(bitmapList, pics);
        imageAdapter.notifyDataSetChanged();

    }


    /**
     * 弹出选择照片的对话框
     */
    protected void showChoose() {

        new ActionSheetDialog(this)
                .builder()
                .setCancelable(true)
                .setCanceledOnTouchOutside(true)
                .addSheetItem("拍照", ActionSheetDialog.SheetItemColor.Blue,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                // 拍照
                                getTakePhoto();

                            }

                        })
                .addSheetItem("去相册选择", ActionSheetDialog.SheetItemColor.Blue,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                // 从相册中选择
                                getFromPhotoAlbum();
                            }
                        }).show();

    }


    /**
     * 从相册中选择
     */
    private void getFromPhotoAlbum() {

        Intent intent = new Intent(this, ChoosePhotoActivity.class);
        startActivityForResult(intent, PHOTO_ALBUM_CODE);

    }

    /**
     * 拍照
     */
    private void getTakePhoto() {

        String cacheDir = Environment.getExternalStorageDirectory().getPath() + "/mlxCache";
        File photoFile = new File(cacheDir);
        //文件夹不存在就创建文件夹
        if (!photoFile.exists()) {
            photoFile.mkdirs();
        }
        //创建存放图片的jpg文件
        currentFile = new File(photoFile, System.currentTimeMillis() + ".jpg");

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(currentFile));
        startActivityForResult(intent, TAKE_PHOTO_CODE);

    }

    /**
     * 放弃编辑
     */
    private void abandonEdit() {

        //如果用户未编辑过内容, 直接退出
        if (CommonUtils.isNull(tv_classify.getText().toString().trim()) && CommonUtils.isNull(tv_receivers.getText().toString().trim())
                && CommonUtils.isNull(et_title.getText().toString().trim()) && CommonUtils.isNull(et_content.getText().toString().trim()) &&
                gv_photos.getChildCount() == 1) {

            finish();

        } else {
            //用户编辑过,给出提示
            new AlertDialog.Builder(this).setMessage("要放弃本次编辑吗").setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    finish();
                }
            }).show();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:

                abandonEdit();

                break;

        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //清除图片
        MyAdapter.mSelectedImage.clear();

        mApplication.cancelPendingRequests(getClass().getName());

    }

}
